<?php declare(strict_types=1);

namespace App\Bac\Model;

use App\Helper\RespHelper;
use Hyperf\Validation\Rule;
use App\Helper\FormValidator;

class Config extends \App\Model\Config
{

    public function map(): array
    {
        return RespHelper::success($this->getCacheMap());
    }

    public function list(array $params): array
    {
        [$page, $size] = getPageFormParams($params);
        $name = trim((string)@$params['name']);
        $label = trim((string)@$params['label']);
        $query = self::query();
        $name && $query->whereRaw("name like '{$name}%'");
        $label && $query->whereRaw("label like '{$label}%'");
        $total = $query->count();
        $query->offset(($page - 1) * $size)->limit($size);
        $rows = $query->get()->toArray();
        return RespHelper::success(compact('total', 'rows'));
    }

    protected function getFormRules(): array
    {
        return [
            'name' => 'required|string|max:20',
            'label' => ['required', 'string', 'max:20'],
            'value' => 'present|string|max:1000',
            'type' => ['required', 'integer', Rule::in(self::TYPE_OPTIONS)],
            'desc' => 'present|string|max:1000',
        ];
    }

    public function saveRow(array $params, int $id = null): array
    {
        $validator = make(FormValidator::class);
        $rules = $this->getFormRules();
        if ($id) {
            $rules['label'][] = Rule::unique('configs', 'label')->ignore($id);
        } else {
            $rules['label'][] = Rule::unique('configs', 'label');
        }
        $params = $validator->validate($params, $rules);
        if ($id) {
            $model = self::find($id);
            if (!$model) return RespHelper::notfound();
        } else {
            $model = new self();
            $model->created_at = time();
        }
        foreach (array_keys($rules) as $key) {
            $model->$key = $params[$key];
        }
        $model->updated_at = time();
        if ($model->save()) {
            return RespHelper::success(null, $id ? '修改成功' : '添加成功');
        }
        return RespHelper::fail();
    }

    public function deleteRow(int $id): array
    {
        $model = self::query()->find($id);
        if (!$model) {
            return RespHelper::notfound();
        }
        if ($model->delete()) {
            return RespHelper::success();
        }
        return RespHelper::fail();
    }

}